package com.springcloud.controller;

import com.springcloud.feignservice.FeignService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author: 顾志杰
 */
@RestController
public class Controller {

    @Autowired
    private FeignService feignService;

    @GetMapping("sayHi")
    public String sayHi(){
        return feignService.sayHi();
    }


    @PostMapping("fileTest")
    public String fileTest(MultipartFile multipartFile) throws IOException {
      MultipartFile multipartFile1 = getMultipartFile(multipartFile.getInputStream(), "aa.png");

      feignService.fileTest(multipartFile1);
      return "ok";
    }


  /**
   * 获取封装得MultipartFile
   *
   * @param inputStream inputStream
   * @param fileName    fileName
   * @return MultipartFile
   */
  public MultipartFile getMultipartFile(InputStream inputStream, String fileName) {
    FileItem fileItem = createFileItem(inputStream, fileName);
    //CommonsMultipartFile是feign对multipartFile的封装，但是要FileItem类对象
    return new CommonsMultipartFile(fileItem);
  }


  /**
   * FileItem类对象创建
   *
   * @param inputStream inputStream
   * @param fileName    fileName
   * @return FileItem
   */
  public FileItem createFileItem(InputStream inputStream, String fileName) {
    FileItemFactory factory = new DiskFileItemFactory(16, null);
    String textFieldName = "multipartFile";
    FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
    int bytesRead = 0;
    byte[] buffer = new byte[8192];
    OutputStream os = null;
    //使用输出流输出输入流的字节
    try {
      os = item.getOutputStream();
      while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
        os.write(buffer, 0, bytesRead);
      }
      inputStream.close();
    } catch (IOException e) {

      throw new IllegalArgumentException("文件上传失败");
    } finally {
      if (os != null) {
        try {
          os.close();
        } catch (IOException e) {


        }
      }
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {

        }
      }
    }

    return item;
  }
}
